/*
 * ------------------------------------------------------------------
 * Copyright © 2017 Hangzhou DtDream Technology Co.,Lt d. All rights reserved.
 * ------------------------------------------------------------------
 *       Product:
 *   Module Name:
 *  Date Created: 2023/10/7
 *   Description:
 * ------------------------------------------------------------------
 * Modification History
 * DATE            Name           Description
 * ------------------------------------------------------------------
 * 2023/10/7    小谷 g2038          created
 * ------------------------------------------------------------------
 */
package com.flynn.rock.system.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.flynn.rock.enums.system.NoIdentifierType;
import com.flynn.rock.system.entity.SysNoIdentifierEntity;
import com.flynn.rock.system.repository.SysNoIdentifierRepository;
import com.flynn.rock.system.service.SysNoIdentifierService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@Service
public class SysNoIdentifierServiceImpl implements SysNoIdentifierService {

    private static final DateTimeFormatter DAY_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    @Resource
    private SysNoIdentifierRepository sysNoIdentifierRepository;

    @Override
    public synchronized String getNoIdentifier(NoIdentifierType identifierType) {
        String dayTime = LocalDateTimeUtil.format(LocalDateTime.now(), DAY_DATETIME_FORMATTER);
        String noIdentifier = identifierType.getPrefix() + dayTime;
        SysNoIdentifierEntity entity = sysNoIdentifierRepository.findByDayTimeAndNoIdType(dayTime, identifierType);
        if (Objects.isNull(entity)) {
            entity = new SysNoIdentifierEntity(1L, dayTime, identifierType);
        } else {
            entity.setIdentifier(entity.getIdentifier() + 1);
        }
        entity = sysNoIdentifierRepository.save(entity);
        if (entity.getIdentifier() < 10000) {
            DecimalFormat noIdFormat = new DecimalFormat("0000");
            noIdentifier += noIdFormat.format(entity.getIdentifier());
        } else {
            noIdentifier += entity.getIdentifier();
        }
        return noIdentifier;
    }
}
